<template>
  <el-dialog
    v-model="dialog.visible"
    :title="dialog.title"
    width="50%"
    style="height: 60vh"
    :before-close="handleCloseDialog"
  >
    <el-form
      ref="roleFormRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      class="internal-from"
    >
      <el-form-item
        v-for="item in column"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
      >
        <el-input
          v-if="['input', 'textarea'].includes(item.type)"
          v-model="formData[item.prop]"
          :type="item.type"
          :autosize="{ minRows: 5 }"
          size="large"
        />
        <el-date-picker
          v-if="['date', 'datetime'].includes(item.type)"
          v-model="formData[item.prop]"
          :type="item.type"
          value-format="YYYY-MM-DD"
          size="large"
        />
        <el-upload
          v-if="item.type === 'upload'"
          ref="uploadRef"
          v-model:file-list="formData[item.prop]"
          action="#"
          :on-success="handleSuccess"
          :on-error="handleError"
          :http-request="customUpload"
          :on-remove="handleRemove"
          style="width: 80%"
        >
          <el-button
            style="margin-left: 10px"
            type="primary"
            @click="submitUpload"
            :loading="loadingUpload"
          >
            上传
          </el-button>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCloseDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
const props = defineProps({
  formData: {
    required: true,
    type: Object,
    default() {
      return {};
    },
  },
  rules: {
    type: Object,
    default() {
      return {};
    },
  },
  column: {
    required: true,
    type: Array,
    default() {
      return [];
    },
  },
  dialog: {
    required: true,
    type: Object,
    default() {
      return {
        title: "",
        visible: false,
      };
    },
  },
});

const emit = defineEmits(["handleSubmit", "refreshList"]);
import { ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import ManageAPI from "../../api/manage";
import { ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();
const { VITE_APP_API_URL, VITE_APP_BASE_API } = import.meta.env;

const roleFormRef = ref(null);
const uploadRef = ref(null);
const loadingUpload = ref(false);

const submitUpload = () => {
  uploadRef.value?.submit();
};
function customUpload(request) {
  loadingUpload.value = true;
  const formData = new FormData();
  formData.append("file", request.file);
  formData.append("objid", props.formData.id || "");

  // 使用自己的上传方法，例如使用axios
  ManageAPI.uploadFile(formData)
    .then((response) => {
      // 上传成功处理逻辑
      request.onSuccess(response.data);
    })
    .catch((error) => {
      // 上传失败处理逻辑
      request.onError(error);
    })
    .finally(() => (loadingUpload.value = false));
}
function handleSuccess(response, file, fileList) {
  ElMessage.success("上传成功");
  // 成功处理逻辑
}
function handleError(err, file, fileList) {
  ElMessage.error("err");
  // 错误处理逻辑
}

// 附件删除
const handleRemove = (file) => {
  ManageAPI.deleteFile({ id: file.id })
    .then((res) => {
      console.log(res);
      if (res.code === 200) {
        ElMessage.success("删除成功");
      } else {
        ElMessage.error(res.data);
      }
    })
    .catch((error) => {
      ElMessage.error(error);
      // 处理上传失败的错误
    });
};

/** 提交表单 */
function handleSubmit() {
  roleFormRef.value.validate((valid) => {
    if (valid) {
      //   loading.value = true;
      const { id, record_date, title, details, file_list, remark } =
        props.formData;
      const dict = [
        "praise",
        "punish",
        "propagandaandeducation",
        "complainthandling",
      ];
      const type_ = dict.indexOf(route.path.slice(1)) + 1;
      const fileids = file_list
        .map((item) => item.response?.id || item.id)
        .join(",");
      if (id) {
        const payload = {
          id, //必传。数据id
          title, //必传。标题
          details, //必传。详情
          remark, //必传。备注
          record_date, //必传。发生时间
        };
        ManageAPI.updateInternal(payload)
          .then((res) => {
            handleCloseDialog();
            if (res.code === 200) {
              ElMessage.success("修改成功");
              handleCloseDialog();
            } else {
              ElMessage.error(res.data);
            }
          })
          .finally(() => {
            // loading.value = false;
          });
      } else {
        const payload = {
          type_, //必传。类型：1-表扬数据 2-惩罚数据 3-宣教活动 4-投诉及处置
          title, //必传。标题
          details, //必传。详情
          remark, //必传。备注
          record_date, //必传。发生时间
          fileids, //必传。添加场景下附件的id集合，多个附件id用逗号分隔
        };
        ManageAPI.addInternal(payload)
          .then((res) => {
            if (res.code === 200) {
              ElMessage.success("新增成功");
              handleCloseDialog();
            } else {
              ElMessage.error(res.data);
            }
          })
          .finally(() => {
            // loading.value = false;
          });
      }
    }
  });
}

/** 关闭弹窗 */
function handleCloseDialog() {
  props.dialog.visible = false;

  roleFormRef.value?.resetFields();
  roleFormRef.value?.clearValidate();
  Object.keys(props.formData).forEach((key) => {
    switch (key) {
      case "file_list":
        props.formData[key] = [];
        break;
      case "record_date":
        break;
      default:
        props.formData[key] = "";
        break;
    }
  });
  emit("refreshList");
}
</script>
<style lang="scss" scoped>
.internal-from {
  :deep(.el-date-editor.el-input),
  :deep(.el-date-editor.el-input__wrapper) {
    width: 100%;
  }
  .file-list {
    list-style: none;
    padding: 0;
    li {
      cursor: pointer;
      margin: 0;
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }
}
</style>
